package tools

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"io/ioutil"
	"net/http"
	"time"
)

type RequestBody struct {
	Touser  []string `json:"touser"`
	Msgtype string   `json:"msgtype"`
	Text    txt      `json:"text"`
}
type txt struct {
	Content string `json:"content"`
}
type result struct {
	Access_token string `json:"access_token"`
	Expires_in   int    `json:"expires_in"`
}

type Song struct {
	ID    int
	Link  string
	Title string
}

var dbtest *gorm.DB

const name = "root"
const password = ""

func Postforuser() {
	dns := name + ":" + password + "@(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local"
	dbtest, _ = gorm.Open("mysql", dns)

	test := RequestBody{
		Touser:  []string{"og9FD6sEiM6MzuAcOEasYUT1Ps7w", "og9FD6jF2ySbTEDTCaud8EA4awUQ"},
		Msgtype: "text",
		Text: txt{
			Content: getcontent(),
		},
	}

	result1, err1 := json.Marshal(test)
	res := getacc()

	if err1 != nil {
		fmt.Println(err1)
		return
	}

	url := "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + res.Access_token

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(result1))
	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)

	defer resp.Body.Close()
	_, _ = ioutil.ReadAll(resp.Body)
	time.AfterFunc(10*time.Minute, Postforuser)

}

func getacc() *result {
	APPID := "wx397a6205ea6773dc"
	SECRET := "fcab2e136d735df1ea0caca1107158e9"
	resp, _ := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET)

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	var res result
	_ = json.Unmarshal(body, &res)

	return &res
}

func getcontent() string {
	// 根据struct创建表users
	dbtest.AutoMigrate(&Song{})
	var s Song
	dbtest.First(&s)
	return "今日热歌榜第一名推荐歌曲名称:" + s.Title + ";链接为:" + s.Link
}
